package com.itheima.service.impl;

import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.constants.BehaviorConstants;
import com.itheima.Utils.UserThreadLocal;
import com.itheima.service.ApCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author yunfei
 * @date 2022年10月25日 22:16
 */
@Service
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        /* 固定前缀+用户ID  {点赞_文章id:1,阅读_文章id:1} */
        if (dto.getOperation() == 0) {
            // 先查询自己是否收藏过
            Boolean hasKey = redisTemplate.opsForHash().hasKey(BehaviorConstants.USER_BEHAVIOR + UserThreadLocal.get(),
                    BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId());
            if (hasKey) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
            redisTemplate.opsForHash().put(BehaviorConstants.USER_BEHAVIOR + UserThreadLocal.get(),
                    BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId(), "1");
        } else {
            redisTemplate.opsForHash().delete(BehaviorConstants.USER_BEHAVIOR + UserThreadLocal.get(),
                    BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
